package com.qianbao.components.excepion;


import com.qianbao.components.svresut.Result;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
@ResponseBody
public class CommonExceptionHandler {


    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e){

        e.printStackTrace();

        String message;
        if (e.getMessage() != null && e.getMessage().length() > 0){
            message = e.getMessage();
        }else {
            message = ExceptionEnum.Request_Fail.getMessage();
        }

        return Result.fail(ExceptionEnum.Request_Fail.getCode(),message);
    }


    @ExceptionHandler(CommonException.class)
    public Result exceptionHandler(CommonException e){

        e.printStackTrace();

        return Result.fail(e.getCode(),e.getMessage());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result exceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();

        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        String tips = ExceptionEnum.Request_Params_Invalid.getMessage();
        if (errors.size() > 0) {
            tips = errors.get(0).getDefaultMessage();
        }

        return Result.fail(ExceptionEnum.Request_Params_Invalid.getCode(),tips);
    }






}
